<template>
  <div class="search-box">
    <el-input v-if="!searchClick && inputData == ''" class="search" placeholder="输入职业关键词，查看职业概况"
      prefix-icon="el-icon-search" @focus="searchFocus" v-model="inputData" @click.stop="
        () => {
          return;
        }
      ">
    </el-input>
    <el-autocomplete v-else :debounce="0" id="searchInput" class="search searchBlue" placeholder="" @focus="searchFocus"
      @select="inputSelect" @keyup.enter.native="enterSelect" v-model="inputData" :fetch-suggestions="querySearchAsync"
      ref="greenFocus" :trigger-on-focus="true" :popper-class="noData ? 'platform-auto-complete' : ''"
      value-key="positionName" clearable>
      <el-button slot="append" class="searchButton" @click.stop="search">
        搜索</el-button>
      <template slot-scope="{ item }">
        <div v-html="formateText(item.positionName)"></div>
        {{ noData ? item.default : "" }}
      </template>
    </el-autocomplete>
    <div class="historyWords" v-if="historyWords.length > 0 && !hideHistory">
      <div class="wordsItem" v-for="(item, index) in historyWords" :key="index" :title="item"
        @click="clickHistory(item)">
        {{ item }}
      </div>
      <div class="wordsItemDelete" @click="deleteAllHistory">
        <i class="el-icon-delete"></i>
      </div>
    </div>
  </div>
</template>

<script>
import antiShake from "../../../utils/antiShake.js";
import { matchPositionList } from "@/api/home.js";
export default {
  props: {
    hideHistory: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      inputData: "",
      searchClick: false,
      automatedList: [{ default: "输入职业进行搜索" }],
      historyWords: [],
      noData: true, // 是否匹配到数据了
    };
  },
  methods: {
    clickHistory(item) {
      this.inputData = item;
      this.changeSelect(function (item) {
        console.log(item);
      });
    },
    deleteAllHistory() {
      this.historyWords = [];
      localStorage.setItem("historyWords", []);
    },
    search() {
      this.$refs.greenFocus.activated = false;
      if (this.inputData != "") {
        this.searchByInputData();
        console.log(this.automatedList);
        if (this.automatedList[0].ylPositionId) {
          this.routerToDetail(this.automatedList[0]);
        }
      }
    },
    searchByInputData() {
      if (!this.inputData.match(/^[ ]*$/)) {
        this.$emit("getInputData", this.inputData);
        let index = this.historyWords.indexOf(this.inputData);
        if (index >= 0) {
          this.historyWords.splice(index, 1);
        }
        this.historyWords.unshift(this.inputData);
        // if (this.historyWords.length > 6) {
        //   this.historyWords = this.historyWords.slice(0, 5);
        // }
        this.$nextTick(() => {
          this.historyWordsMax();
        });
      }
    },
    // onScroll() {
    //   if (this.hideHistory) return;
    //   const scrollTop = document.documentElement.scrollTop;
    //   let history = document.getElementsByClassName("historyWords")[0];
    //   if (history) {
    //     history.style.transform = `translateY(${-scrollTop}px)`;
    //   }
    // },
    searchFocus() {
      this.searchClick = true;
      setTimeout(() => {
        this.$refs.greenFocus.focus();
      }, 200);
    },
    changeSelect(cb) {
      //这里获取联想的数据列表
      if (this.inputData != "") {
        // let formData = new FormData();
        // formData.append("matchTitle", this.inputData);
        matchPositionList({
          matchTitle: this.inputData,
        }).then((res) => {
          if (res.code == 200) {
            this.automatedList = res.data;
            if (this.automatedList.length == 0) {
              this.automatedList = [{ default: "暂无匹配职业" }];
              this.noData = true;
            }
            //console.log("this.automatedList11", this.automatedList);
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
              "this.automatedList即将输出", this.automatedList;
              cb(this.automatedList);
            }, 100);
          }
        });
      }
    },
    //点击搜索框之外，判断搜索框类型
    clickInputOutside() {
      // if (this.searchClick) {
      //   this.$refs.greenFocus.activated = false;
      // }
      //console.log("this.inputData", this.inputData);
      if (this.inputData == "") {
        this.searchClick = false;
      }
    },
    //失去焦点，收回下拉框
    // CollapseDropdownBox() {
    //   setTimeout(() => {
    //     this.$refs.greenFocus.activated = false;
    //   }, 100);
    // },
    inputSelect(e) {
      if (e.ylPositionId) {
        this.routerToDetail(e);
      }
    },
    enterSelect() {
      if (this.inputData == "") {
        return;
      } else {
        this.search();
      }
    },
    routerToDetail(e) {
      let routeData = this.$router.resolve({
        path: "/position-detail",
        query: {
          // fatherTitle: `${e.topTitle} · ${e.parentTitle}`,
          id: e.ylPositionId,
          name: e.positionName,
          superToken: this.$route.query.superToken || "",
          SecretKey: this.$route.query.SecretKey || "",
          customerName: this.$route.query.customerName,
        },
      });
      window.open(routeData.href, "_blank");
      this.searchByInputData();
    },
    querySearchAsync(queryString, cb) {
      if (this.inputData == "") {
        this.automatedList = [{ default: "输入职业进行搜索" }];
        cb([{ default: "输入职业进行搜索" }]);
      } else {
        antiShake(() => {
          //console.log("调用");
          this.changeSelect(cb);
        }, 1000).call(this);
      }
    },
    formateText(content) {
      if (content && content != "") {
        let text = this.inputData;
        let regStr = `(${text})`;
        let reg = new RegExp(regStr, "g");
        // 正则替换，关键词飘红
        return content.replace(
          reg,
          '<span style="color:#0B6EFF;">' + text + "</span>"
        );
      }
    },
    historyWordsMax() {
      const el = document.getElementsByClassName("wordsItem");
      let totalWidth = 0;
      el.forEach((item, index) => {
        totalWidth += item.clientWidth;
        if (totalWidth >= 550) {
          if (index != 0) {
            this.historyWords.pop();
          } else {
            let history = document.getElementsByClassName("wordsItem")[0];
            history.style.overflow = `hidden`;
            history.style.whiteSpace = `nowrap`;
            history.style.textOverflow = `ellipsis`;
          }
          return;
        }
      });
      localStorage.setItem("historyWords", JSON.stringify(this.historyWords));
    },
  },
  mounted() {
    // window.addEventListener("scroll", this.onScroll);
    if (localStorage.getItem("historyWords")) {
      this.historyWords = JSON.parse(localStorage.getItem("historyWords"));
      this.$nextTick(() => {
        this.historyWordsMax();
      });
    } else {
      this.historyWords = [];
    }
  },
  // destroy() {
  //   window.removeEventListener("scroll", this.onScroll);
  // },
};
</script>

<style scoped lang="scss">
.search-box {
  width: 100%;
  margin-top: 28px;
  display: flex;
  align-items: center;
  flex-direction: column;
  position: sticky;
  top: 11px;
  z-index: 2;
  .search {
    width: 600px;
    z-index: 2;
    ::v-deep .el-input__inner {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      background: rgba(255, 255, 255, 0.2);
      border: 1px #5e6d84 solid;
      padding-left: 40px;
    }
    ::v-deep .el-input__prefix {
      left: 14px;
    }
    ::v-deep .el-icon-search:before {
      font-size: 17px;
    }
  }
  .searchBlue {
    z-index: 2;
    ::v-deep .el-input__inner {
      border: #0b6eff 2.5px solid;
      border-radius: 21px 0 0 21px;
      background: #fff;
      transition: 0.5s;
      padding-left: 20px;
    }

    ::v-deep .el-input__inner:focus {
      border-radius: 21px 0 0 0px;
      border-bottom: 1px;
      transition: 0s;
    }
    .searchButton {
      background: #0b6eff;
      color: #fff;
      width: 88px;
      border-radius: 0 21px 21px 0;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      letter-spacing: 5px;
      height: 40px;
    }
    ::v-deep .el-input-group__append,
    .el-input-group__prepend {
      background: none;
      border: none;
    }
  }
  .historyWords {
    width: 600px;
    position: relative;
    padding: 10px 20px;
    margin-right: 20px;
    display: flex;
    // overflow: hidden;
    white-space: nowrap;
    // text-overflow: ellipsis;
    .wordsItem {
      color: #bfbfbf;
      font-size: 14px;
      background: rgba(0, 0, 0, 0.15);
      padding: 3px 10px;
      border-radius: 6px;
      margin: 0 5px;
      cursor: pointer;
      max-width: 560px;
    }
    .wordsItemDelete {
      color: #bfbfbf;
      font-size: 14px;
      background: rgba(0, 0, 0, 0.15);
      padding: 3px 10px;
      border-radius: 6px;
      margin: 0 5px;
      cursor: pointer;
    }
  }
}
// .historyWords::-webkit-scrollbar {
//   width: 0 !important;
// }
// /*IE 10+*/
// .historyWords {
//   -ms-overflow-style: none;
// }
// /*Firefox*/
// .historyWords {
//   overflow: -moz-scrollbars-none;
// }
::v-deep .el-input__icon {
  height: 0;
}
::v-deep .el-input__inner {
  // box-shadow: 0px 2px 4px 0px rgba(225, 225, 225, 0.5);
  border-radius: 21px;
}
::v-deep .el-input__suffix {
  .el-icon-circle-close:before {
    content: "×";
    font-size: 15px;
  }
}
</style>
<style>
.el-popper[x-placement^="bottom"] {
  margin-top: 0px;
}
.el-autocomplete-suggestion {
  margin: 0px;
  border: #0b6eff 2.5px solid;
  border-top: 0px solid;
  border-radius: 0 0 21px 21px;
  transition: 0s;
  box-shadow: none;
}
.el-autocomplete-suggestion::before {
  content: "";
  display: inline-block;
  width: 94%;
  height: 1px;
  background: #e9e9e9;
  position: absolute;
  top: 0px;
  left: 3%;
  border-radius: 8px;
}
/* .el-autocomplete-suggestion li:hover::after {
  content: "点击或回车进入详情页";
  position: absolute;
  top: 0px;
  right: 10px;
  font-size: 12px;
} */
.el-autocomplete-suggestion li:hover {
  position: relative;
  margin: 0 10px;
}

/* 消除小三角 */
.el-popper[x-placement^="bottom"] .popper__arrow {
  border: none;
}
.el-popper[x-placement^="bottom"] .popper__arrow::after {
  border: none;
}
</style>
